import { computed } from 'vue'
import { useUserStore } from '../store/user'
import { useRoleStore, ROLE_CODES } from '../store/role'

/**
 * 角色相关的组合式函数
 * @returns 角色相关的计算属性和方法
 */
export function useRole() {
  const userStore = useUserStore()
  const roleStore = useRoleStore()
  
  // 获取用户角色列表
  const userRoles = computed(() => userStore.getUserInfo.roles || [])
  
  // 获取用户角色对象列表
  const userRoleObjects = computed(() => userStore.getUserInfo.roleObjects || [])
  
  // 获取角色枚举
  const roleEnums = computed(() => roleStore.getRoleEnums)
  
  // 判断用户是否有指定角色
  const hasRole = (role: string) => {
    return userRoles.value.includes(role) || userRoles.value.includes(ROLE_CODES.SUPER_ADMIN)
  }
  
  // 判断用户是否有指定角色中的任意一个
  const hasAnyRole = (roles: string[]) => {
    return roles.some(role => userRoles.value.includes(role)) || userRoles.value.includes(ROLE_CODES.SUPER_ADMIN)
  }
  
  // 判断用户是否有指定角色中的所有角色
  const hasAllRoles = (roles: string[]) => {
    return roles.every(role => userRoles.value.includes(role)) || userRoles.value.includes(ROLE_CODES.SUPER_ADMIN)
  }
  
  // 判断用户是否是超级管理员
  const isSuperAdmin = computed(() => userRoles.value.includes(ROLE_CODES.SUPER_ADMIN))
  
  // 判断用户是否是教师
  const isTeacher = computed(() => userRoles.value.includes(ROLE_CODES.TEACHER))
  
  // 获取角色名称
  const getRoleName = (roleCode: string) => {
    // 先从用户角色对象中查找
    const userRole = userRoleObjects.value.find(r => r.code === roleCode)
    if (userRole) {
      return userRole.name
    }
    
    // 再从角色枚举中查找
    return roleStore.getRoleName(roleCode)
  }
  
  // 加载角色枚举
  const loadRoleEnums = async () => {
    return await roleStore.loadRoleEnums()
  }
  
  return {
    userRoles,
    userRoleObjects,
    roleEnums,
    hasRole,
    hasAnyRole,
    hasAllRoles,
    isSuperAdmin,
    isTeacher,
    getRoleName,
    loadRoleEnums
  }
} 